export interface Coordinates {
  lat: number; // 纬度
  lon: number; // 经度
}

function haversineDistance(coord1: Coordinates, coord2: Coordinates, unit: 'km' | 'm' = 'km') {
  const rad = (x: number) => x * Math.PI / 180;

  var R = 6371; // 地球半径单位为公里
  if (unit === 'm') {
    R = 3958; // 地球半径单位为英里
  }

  const lat1 = rad(coord1.lat);
  const lat2 = rad(coord2.lat);
  const a = Math.sin((lat2 - lat1) / 2) ** 2 +
    Math.cos(lat1) * Math.cos(lat2) *
    Math.sin((rad(coord2.lon) - rad(coord1.lon)) / 2) ** 2;
  const distance = 2 * R * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

  return distance;
}

// 使用示例
const coord1 = { lat: 45.7778, lon: 21.2222 };
const coord2 = { lat: 46.7778, lon: 22.2222 };

const distance = haversineDistance(coord1, coord2, 'km'); // 返回两点之间的距离，单位为公里
console.log(distance);

/**
 * 地图工具
 */
class MapHelper {
  private static instance: MapHelper

  public static getInstance(): MapHelper {
    if (!this.instance) {
      this.instance = new MapHelper()
    }
    return this.instance
  }

  public getDistance(coord1: Coordinates, coord2: Coordinates) {
    const rad = (x: number) => x * Math.PI / 180;

    var R = 6371000; // 地球半径单位为公里

    const lat1 = rad(coord1.lat);
    const lat2 = rad(coord2.lat);
    const a = Math.sin((lat2 - lat1) / 2) ** 2 +
      Math.cos(lat1) * Math.cos(lat2) *
      Math.sin((rad(coord2.lon) - rad(coord1.lon)) / 2) ** 2;
    const distance = 2 * R * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

    return distance;
  }

  public test(num: number) {
    return num + num;
  }
}

export const mapHelper = MapHelper.getInstance()